from qiniu import Auth, put_data, etag
import qiniu.config


def upload(bucket_name="images-home", key=None, data=None):
    # 填写accecc_key和secret_key
    AK = "76Yu0cnsWOf0zECf3YO7y-etLb7WrZ2flxbXEtez"
    SK = "2x68c0VCUNsX0UUUGbY4SShauUkpBwzFQQ5ErzLc"

    # 构建健全对象
    q = Auth(AK, SK)

    # 要上传的空间
    # bucket_name = "images-home"

    # 上传后保存到文件名
    # key = "*.png"

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)

    # 要上传文件的本地路径
    # localfile = './sync/bbb.jpg'

    ret, info = put_data(token, key, data)
    print(ret, info)
    # ret : {'hash': 'FqoxknG28t8pQLIX4JfqDYP53Ffx', 'key': 'dj_2.jpg'}
    # info: _ResponseInfo__response:<Response [200]>, exception:None, status_code:200, text_body:{"hash":"FqoxknG28t8pQLIX4JfqDYP53Ffx","key":"dj_2.jpg"}, req_id:qhkAAAAZ9f4hwRAW, x_log:X-Log
    if info.status_code == 200:
        return "http://qamsij369.bkt.clouddn.com/" + ret.get("key")
    else:
        raise Exception("文件上传失败")


if __name__ == '__main__':
    filename = "dj_2.jpg"
    try:
        with open(filename, "rb") as fp:
            data = fp.read()
            access_url = upload(key=filename, data=data)
    except Exception as e:
        print(e)
    else:
        print(access_url)



